﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Demo.Api.Data;
using Demo.Api.Entities;
using KmFlow;
using Microsoft.EntityFrameworkCore;

namespace Demo.Api.Services
{
    public class LineRepository : Repository<LineDo>
    {
        public LineRepository(DemoDbContext context) : base(context)
        {
            DataSet = Context.TabLines;
        }
        public async Task<IEnumerable<LineDo>> GetsAsync(long flowId)
        {
            return await DataSet.Where(x => x.FlowChartId == flowId).ToListAsync();
        }

        public override Task<bool> Add(LineDo data)
        {
            if (data == null)
                throw new ArgumentNullException(nameof(data));
            if (data.TailNodeId == 0 || data.HeadNodeId == 0)
                throw new ArgumentException("线不存在头节点或者尾节点");
            var repeatCheck = DataSet
                .Count(x => x.HeadNodeId == data.HeadNodeId && x.TailNodeId == data.TailNodeId);
            if (repeatCheck > 0)
            {
                throw new ArgumentException("线重复");
            }
            var mergeNodeOnlyOneLineCheck = from l in Context.TabLines
                                            join n in Context.Nodes on l.TailNodeId equals n.Id
                                            where l.TailNodeId == data.TailNodeId && n.NodeType == (long)NodeType.Merge
                                            select new { l.Id };
            if (mergeNodeOnlyOneLineCheck.Any())
            {
                throw new ArgumentException("分流节点只能有一根外向连线");
            }
            return base.Add(data);
        }
    }
}